import datetime

from common.exceptions import NotFound, AuthorizationFailed
from model.book import BookSpaceModel
from model.team import TeamSpaceModel
from util.auth_validate import auth_validate
from util.db import Cursor
from util.db import Cursor
from flask import session


class ArticleModel:

    def __init__(self, article_id: str):
        self.article_id = article_id

    @staticmethod
    def __get_article_content_without_login(id):
        with Cursor() as cursor:
            sql = """select * from yugong_article as a
                    LEFT JOIN 
                    (select id as user_id, username from yugong_user) as b 
                    ON a.create_person = b.user_id
                    where id=%s and auth=0
                    order by sort asc"""
            cursor.execute(sql, [id])
            res = cursor.fetchall()
        if not res:
            raise AuthorizationFailed('抱歉,您暂无权限或访问的资源不存在')
        data = res[0]
        data['role'] = 'reader'
        data['read_time'] = str(datetime.timedelta(seconds=data['read_time']))
        data['create_time'] = str(data['create_time'])
        data['update_time'] = str(data['update_time'])
        return data
    @staticmethod
    def __get_article_content_with_login(id):
        user_id = session.get('user_id')
        team_role = TeamSpaceModel.get_team_role(id=id, id_type='article')
        with Cursor() as cursor:
            sql = """select * from yugong_article as a
                    LEFT JOIN 
                    (select id as user_id, username from yugong_user) as b 
                    ON a.create_person = b.user_id
                    where id=%s and (auth!=1 or create_person=%s)
                    order by sort asc"""
            cursor.execute(sql, [id, user_id])
            res = cursor.fetchall()
        data = res[0]
        if team_role:
            data['role'] = team_role
        elif data['auth'] == 0:
            data['role'] = 'reader'
        else:
            raise AuthorizationFailed()
        data['read_time'] = str(datetime.timedelta(seconds=data['read_time']))
        data['create_time'] = str(data['create_time'])
        data['update_time'] = str(data['update_time'])
        return data

    @staticmethod
    def get_article_content(id):
        login_status = session.get('login_status')
        if login_status:
            return ArticleModel.__get_article_content_with_login(id)
        return ArticleModel.__get_article_content_without_login(id)


    @property
    def team_id(self) -> int:
        with Cursor() as cursor:
            sql = """select team_id from yugong_article where article_id=%s"""
            cursor.execute(sql, [self.article_id])
            data = cursor.fetchall()
            return data[0].get('team_id')

    @property
    def book_id(self) -> int:
        with Cursor() as cursor:
            sql = """select book_id from yugong_article where article_id=%s"""
            cursor.execute(sql, [self.article_id])
            data = cursor.fetchall()
            return data[0].get('book_id')

    @staticmethod
    def get_user_article_space():
        with Cursor() as cursor:
            user_id = session.get('user_id')
            sql = """select * from yugong_article where id in (select resource_id from yugong_auth_article where user_id=%s) limit 0, 10"""
            cursor.execute(sql, [user_id])
            data = cursor.fetchall()
        return data

    @staticmethod
    def __get_article_child_without_login(article_id):
        """获取未登录状态下文章的子节点"""
        # 创建资源的时候限制公开、私密、团队等策略
        with Cursor() as cursor:
            # 查询公开的文章
            sql = """select article_id,father_id,child_id,history_id,title,create_person,update_person,status,
                        category,word_count,read_time,create_time,update_time,sort,name,
                        child_num,auth,id,team_id,book_id from `yugong_article`
                     where father_id=%s and auth=0
                     order by sort asc"""
            cursor.execute(sql, [article_id])
            article_list = cursor.fetchall()
            for item in article_list:
                item['role'] = 'reader'
                item['label'] = item['name']
                if item['child_num'] > 0:
                    item['has_child'] = True
                    item['children'] = [{}]
                else:
                    item['has_child'] = False
                    item['children'] = []
        return list(article_list)

    @staticmethod
    def __get_article_child_with_login(article_id):
        """获取登录状态下文章的子节点"""
        user_id = session.get('user_id')
        with Cursor() as cursor:
            # 首先获取主键ID

            sql = """select article_id,father_id,child_id,history_id,title,create_person,update_person,`status`,
                            category,word_count,read_time,create_time,update_time,sort,`name`,
                            child_num,auth,id,team_id,book_id from yugong_article where father_id=%s and (auth != 1 or create_person=%s) 
                            order by sort asc"""
            cursor.execute(sql, [article_id, user_id])
            article_list = cursor.fetchall()
            result = []
            if article_list:
                sql = "select team_id from yugong_article where father_id=%s limit 1"
                cursor.execute(sql, [article_id])
                res = cursor.fetchall()
                team_id = res[0]['team_id']
                role = TeamSpaceModel.get_team_role(id=team_id, id_type='team')
                for item in article_list:
                    if role:
                        item['role'] = role
                    elif item['auth'] == 0:
                        item['role'] = 'reader'
                    else:
                        # 无团队角色且资源未公开
                        continue
                    item['label'] = item['name']

                    if item['child_num'] > 0:
                        item['has_child'] = True
                        item['children'] = [{}]
                    else:
                        item['has_child'] = False
                        item['children'] = []
                    result.append(item)
        return result

    @staticmethod
    def get_article_child(article_id):
        """获取此节点下的子节点"""
        login_status = session.get('login_status')
        if login_status:
            return ArticleModel.__get_article_child_with_login(article_id)
        return ArticleModel.__get_article_child_without_login(article_id)

    @staticmethod
    def get_father_ids(article_id, data, ids):
        with Cursor() as cursor:
            sql = """select father_id from yugong_article where article_id=%s"""
            cursor.execute(sql, [article_id])
            res = cursor.fetchall()
        if res:
            father_id = res[0]['father_id']
            flag = False
            for item in data:
                if item.get('article_id') == father_id:
                    flag = True
                    break
            if str(item.get('book_id')) != father_id:
                ids.insert(0, father_id)
            if not flag:
                ArticleModel.get_father_ids(father_id, data, ids)
            else:
                return

    @staticmethod
    def insert_children_digui(data, ids):
        if not ids:
            return
        id = ids.pop(0)
        res = None
        for item in data:
            if item.get('article_id') == id:
                res = ArticleModel.get_article_child(id)
                item['children'] = res
                break
        if res:
            ArticleModel.insert_children_digui(res, ids)

    @staticmethod
    def get_article_child_digui(book_id, article_id=None):
        data = ArticleModel.get_article_child(book_id)
        if not article_id:
            return data
        else:
            ids = [article_id]
            # 获取所有的节点ID
            ArticleModel.get_father_ids(article_id, data, ids)
            # 节点插入子节点
            ArticleModel.insert_children_digui(data, ids)
        return data

    @staticmethod
    def get_article_info(article_id):
        """获取次节点下的子节点"""
        user_id = session.get('user_id')
        with Cursor() as cursor:
            sql = """select * from yugong_article where `id`=%s"""
            cursor.execute(sql, [article_id])
            article_info = cursor.fetchall()
            for item in article_info:
                item['role'] = TeamSpaceModel.get_team_role(id=article_id, id_type='article')
                item['read_time'] = str(datetime.timedelta(seconds=item['read_time']))
                item['create_time'] = str(item['create_time'])
                item['update_time'] = str(item['update_time'])
                item['label'] = item['name']
                if item['child_num'] > 0:
                    item['has_child'] = True
                    item['children'] = [{}]
                else:
                    item['has_child'] = False
                    item['children'] = []
        return article_info

    @staticmethod
    def __get_book_info_without_login(book_id):
        with Cursor() as cursor:
            sql = """select * from yugong_book where id=%s and auth=0"""
            cursor.execute(sql, [book_id])
            book_info = cursor.fetchall()
        if not book_info:
            raise AuthorizationFailed('抱歉，您暂无访问权限或该知识库不存在')
        for item in book_info:
            item['role'] = 'reader'
            item['create_time'] = str(item['create_time'])
            item['update_time'] = str(item['update_time'])
        return book_info[0]

    @staticmethod
    def __get_book_info_with_login(book_id):
        user_id = session.get('user_id')
        with Cursor() as cursor:
            sql = """select * from yugong_book where id=%s and (auth !=1 or user_id=%s)"""
            cursor.execute(sql, [book_id, user_id])
            book_info = cursor.fetchall()
        if not book_info:
            raise AuthorizationFailed('抱歉，您暂无访问权限或该知识库不存在')
        role = TeamSpaceModel.get_team_role(id=book_id, id_type='book')
        # 如果资源公开，则可以reader角色访问
        # 如果资源未公开，没有团队角色，不可访问
        # 有团队角色，可以团队角色访问
        for item in book_info:
            if role:
                item['role'] = role
            elif item['auth'] == 0:
                item['role'] = 'reader'
            else:
                raise AuthorizationFailed()
            item['article_id'] = item['id']
            item['create_time'] = str(item['create_time'])
            item['update_time'] = str(item['update_time'])
        return book_info[0]
    @staticmethod
    def get_book_info(book_id):
        login_status = session.get('login_status')
        if not login_status:
            return ArticleModel.__get_book_info_without_login(book_id)
        return ArticleModel.__get_book_info_with_login(book_id)

    @staticmethod
    def get_all_book_category(book_id: str, category=None):
        """获取此知识库的所有目录"""
        if category is None:
            category = []
        category = ArticleModel.get_article_child(book_id)
        if not category:
            return []
        else:
            for item in category:
                res = ArticleModel.get_all_book_category(item['article_id'])
                item['children'] = res
        return category


if __name__ == '__main__':
    res = ArticleModel.get_article_child_digui(book_id=43, article_id='article20240712203239068495')
    print(res)
